<?php

namespace App\Api\Three\ShopA;

/**
 * https://docs.qq.com/doc/DRUlEamNJWFFhVmVR
 */

use App\Api\ChannelApi;
use Monolog\Logger;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\RotatingFileHandler;
use Illuminate\Support\Facades\DB;

// use function GuzzleHttp\json_decode;

class TelecomGD extends ChannelApi
{
    protected $model;
    protected $appKey = '';
    protected $url = '';
    protected $secret = '';
    protected $channel = '';
    protected $config = [];
    protected $HTTPOK = 1; //检查接口返回的数据 返回1 代表返回正确
    protected $root;
    protected $log;
    protected $isTrue = true;
    protected $return_message = '';
    protected $onLineNum = '';


    public function __construct($url = '', $str = '')
    {
        $this->pname = 'ATelecomGD';
        $this->log = new Logger('ATelecomGD');
        $this->log->pushHandler(
            (new RotatingFileHandler(storage_path('/logs/ATelecomGD.log'), 14, Logger::DEBUG, true, 0777))->setFormatter(new LineFormatter(null, null, true, true))
        );
        $this->url = $url;
    }
    // 提交到老系统
    public function orderSubmit($array = [])
    {
        // // 暂时先不发送 返回成功
        // 组装提交数据
        $method = '/prod/generate?turbo=1';
        $this->log->info('参数:' . json_encode($array));
        $data = $this->setData($array);
        if (empty($data)) {
            return $this->returnMsg(100, '传递参数为空');
        }
        $strArr = json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);

        $headers = [
            'Content-Type:application/json;charset=utf-8',
            'X-Sign:' . $this->getSign($strArr),
        ];
        // var_dump($this->getSign($strArr));
        $url = $this->url . $method;
        $res =  $this->sendBefare($url, $strArr, $headers);
        $this->log->info('参数:' . ($strArr) . '返回的参数:' . $res);
        // if (is_string($res)) {
        //     $res = json_decode($res, true);
        // }
        if (!empty($res)) {
            return $this->returnMsg(200, '提交成功', ['order_id' => !empty($res) ? $res : '']);
        }
        return $this->returnMsg(100, '提交失败', ['order_id' => !empty($res) ? $res : '']);
    }
    // 不同套餐 设置的参数不一样
    public function setData($data)
    {
        $return = [];
        switch ($data['channel_code']) {
            case '29元314G':
                $return = [
                    'order_data' => [
                        "代理商账号" => "kj-qiaoqiao",
                        "使用人姓名" => "郭德爽",
                        "使用人证件号" => "230182198308280088",
                        "接口下单账号" => 'agentInterface',
                        '异步通知地址' => '',
                        "业务类型" => "赋能产品业务",
                        "办理类型" => "新装主卡",
                        "发票信息" => [
                            '发票投递方式' => '不需要',
                        ],
                        "客户信息" => [
                            "客户类型" => "普通客户",
                            "客户证件号码" => $data['pay_identity'],
                            "客户证件姓名" => $data['pay_name'],
                            "客户证件类型" => "身份证",
                            "联系人" => $data['pay_name'],
                            "联系电话" => $data['pay_phone']
                        ],
                        "揽装信息" => [
                            "协销工号" => "",
                            "揽装工号" => "30940155"
                        ],
                        "物流信息" => [
                            "发货类型" => "同德仓发货",
                            "受理类型" => "不需要受理",
                            "回收资料" => "",
                            "配送公司" => "EMS",
                            "配送失败是否需要回退" => "否",
                            "配送类型" => "普通服务"
                        ],
                        "移动接入" => [
                            [
                                "UIM实物串号" => "",
                                "号码类型" => "主卡",
                                "移动接入号" => "随机",
                                "订购类型" => "新装"
                            ]
                        ],
                        "订单备注" => "",
                        "订单来源单号" => $data['orderno'],
                        "订购产品" => [
                            "AI编码" => 'B2XPT42022110709564111610997',
                            "产品名称" => "【广州】2022版标品39元星卡（预存100抵套内及通行证）",
                            "付费类型" => "预付费",
                            '属性列表' => [
                                [
                                    '属性值' => "13211008822",
                                    '属性名' => "销售人员账号"
                                ]
                            ]
                        ],
                        '配送信息' => [
                            '区' => $data['post_area'],
                            '市' => $data['post_city'],
                            '省' => $data['post_province'],
                            '联系人' => $data['pay_name'],
                            '联系电话' => $data['pay_phone'],
                            '详细地址' => $data['post_address'],
                            '配送产品' => [
                                [
                                    "产品名称" => "分销B2I卡",
                                    "产品数量" => "1",
                                    "产品类型" => "号卡"
                                ],
                                [
                                    "产品名称" => "预存实名激活指引FXZ002",
                                    "产品数量" => "1",
                                    "产品类型" => "礼品"
                                ]
                            ],
                        ],

                    ],
                ];
                break;
            case '30元140G':
                $return = [
                    'order_data' => [
                        "代理商账号" => "kj-qiaoqiao",
                        "使用人姓名" => "郭德爽",
                        "使用人证件号" => "230182198308280088",
                        "接口下单账号" => 'agentInterface',
                        '异步通知地址' => '',
                        "业务类型" => "赋能产品业务",
                        "办理类型" => "新装主卡",
                        "发票信息" => [
                            '发票投递方式' => '不需要',
                        ],
                        "客户信息" => [
                            "客户类型" => "普通客户",
                            "客户证件号码" => $data['pay_identity'],
                            "客户证件姓名" => $data['pay_name'],
                            "客户证件类型" => "身份证",
                            "联系人" => $data['pay_name'],
                            "联系电话" => $data['pay_phone']
                        ],
                        "揽装信息" => [
                            "协销工号" => "",
                            "揽装工号" => "30940155"
                        ],
                        "物流信息" => [
                            "发货类型" => "同德仓发货",
                            "受理类型" => "不需要受理",
                            "回收资料" => "",
                            "配送公司" => "EMS",
                            "配送失败是否需要回退" => "否",
                            "配送类型" => "普通服务"
                        ],
                        "移动接入" => [
                            [
                                "UIM实物串号" => "",
                                "号码类型" => "主卡",
                                "移动接入号" => "随机",
                                "订购类型" => "新装"
                            ]
                        ],
                        "订单备注" => "",
                        "订单来源单号" => $data['orderno'],
                        "订购产品" => [
                            "AI编码" => 'B2XPT220220530091813184840',
                            "产品名称" => "【广州】39元星卡2022版-计划A",
                            "付费类型" => "预付费",
                            '属性列表' => [
                                [
                                    '属性值' => "13211008822",
                                    '属性名' => "销售人员账号"
                                ]
                            ]
                        ],
                        '配送信息' => [
                            '区' => $data['post_area'],
                            '市' => $data['post_city'],
                            '省' => $data['post_province'],
                            '联系人' => $data['pay_name'],
                            '联系电话' => $data['pay_phone'],
                            '详细地址' => $data['post_address'],
                            '配送产品' => [
                                [
                                    "产品名称" => "分销B2I卡",
                                    "产品数量" => "1",
                                    "产品类型" => "号卡"
                                ],
                                [
                                    "产品名称" => "预存实名激活指引FXZ002",
                                    "产品数量" => "1",
                                    "产品类型" => "礼品"
                                ]
                            ],
                        ],

                    ],
                ];
                break;
        }
        return $return;
    }
    // 查询订单 查询
    public function queryOrderStatus($array = [])
    {
        $method = '/prod/query/query-order-info';
        $url = $this->url . $method;
        // var_dump($url);
        // 赋能平台的订单查询
        $data = [
            'route' => '代理商订单信息查询',
            "代理商账号" => "kj-qiaoqiao",
            "使用人证件号" => "230182198308280088",
            "使用人姓名" => "郭德爽",
            "订单编码" => $array['sup_orderno'],
        ];
        $strArr = json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
        $headers = [
            'Content-Type:application/json;charset=utf-8',
            'X-Sign:' . $this->getSign('data=' . urlencode($strArr)),
        ];
        $res = $this->sendBefareGet($url, $strArr, $headers);
        $return = [];
        if (!empty($res) && is_string($res)) {
            $return = json_decode($res, true);
        }

        return $this->returnMsg(200, '查询成功', $return);
    }
    // 处理数据 将数据处理成统一格式
    public function queryOneOrder($array = [])
    {
        $res = $this->queryOrderStatus($array);
        if (empty($res['data'])) {
            return $this->returnMsg(100, '数据为空');
        }
        if (empty($res['data']['data']['q'])) {
            return $this->returnMsg(101, '未查询到数据');
        }
        $getData = $res['data']['data']['q'][0];
        $data = [
            'id' => $getData['uid'],
            'sup_order' => $getData['订单编码'],
            'created_at' => date('Y-m-d H:i:s', strtotime($getData['下单时间'])),
            'order_desc' => $getData['订单当前状态']['订单状态名称'],
            'order_desc_at' => date('Y-m-d H:i:s', strtotime($getData['订单当前状态']['订单当前状态|状态更新时间'])),
            'order_num' => $getData['订单来源2']['订单来源单号'],
            'pagename' => $getData['订购产品']['产品名称'],
            'express_company' => $getData['订单配送方式']['配送公司'],
            'express_number' => !empty($getData['订单配送方式']['配送公司']) ? $getData['订单配送方式']['配送公司'] : '',
            'province' => !empty($getData['收件人地址'][0]['省']) ? $getData['收件人地址'][0]['省'] : '',
            'city' => !empty($getData['收件人地址'][0]['市']) ? $getData['收件人地址'][0]['市'] : '',
            'area' => !empty($getData['收件人地址'][0]['区']) ? $getData['收件人地址'][0]['区'] : '',
            'address' => !empty($getData['收件人地址'][0]['详细地址']) ? $getData['收件人地址'][0]['详细地址'] : '',
        ];
        return $this->returnMsg(200, '查询成功', [$data]);
    }
    public function sendBefare($url, $data, $headers, $isPost = 1)
    {
        // return 1212222222222;
        $curl = curl_init(); // 启动一个CURL会话
        if (!empty($isPost) || $isPost != 1) {
            $url = $url . '?data=' . urlencode($data);
        }
        // var_dump($url, 666666666);
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); // 从证书中检查SSL加密算法是否存在
        // curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        if ($isPost == 1) {
            curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
            curl_setopt($curl, CURLOPT_POSTFIELDS, ($data)); // Post提交的数据包
        }
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
        if (!empty($headers)) {
            curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        }

        $result = curl_exec($curl); // 执行操作
        curl_close($curl); // 关闭CURL会话
        return $result;
    }
    public function sendBefareGet($url, $data, $headers)
    {
        $curl = curl_init(); // 启动一个CURL会话
        $url = $url . '?data=' . urlencode($data);
        // var_dump($url, 666666666);
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); // 从证书中检查SSL加密算法是否存在
        // curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
        if (!empty($headers)) {
            curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        }

        $result = curl_exec($curl); // 执行操作
        // var_dump($result, 111111111);
        curl_close($curl); // 关闭CURL会话
        return $result;
    }
    public function getSign($str)
    {
        if (is_array($str)) {
            $str = json_encode($str, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
        }
        $strs = strtolower(md5($str));
        $getPKey = $this->getPublicKey();
        $key = openssl_pkey_get_public($getPKey);
        $return = openssl_public_encrypt($strs, $crypted, $key);
        if (!$return) {
            return '';
        }
        return base64_encode($crypted);
    }
    public function getPublicKey()
    {
        $str = "-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAok8DnvM2OBwtzNoJb4nA
jn4lgCkSxLyRw5lLiUfsi+40h00CGAC1arvbinTTbtrSnm4YDYlaJwveiOeDKdk0
f2Yglb/8loEbNTqb1OqNxUeM1wYLRBXvAkkZ5fZllajWzFMkoNU/JQ4+T8sMATxm
1d1XRcgM6zlgVwX6siDoLZ5Dm23CTS7SXhyMLtS9cgLefHcOckPQyXoB/IJqb0K1
P0Sk0PE1OSRzpsI9JVzhsSW164fwYpxEbygj9O9JAmAszixwItt2j5zLJ6zRnK3R
OrcAVMN/vpXTN2dCLGZXQrsTK9sAWASzIWTiQRzmnwxsQY7y4u2h+k41n8Z5tw03
wwIDAQAB
-----END PUBLIC KEY-----";
        return $str;
    }
}
